import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import CommonImgsLoad from '@/components/CommonImgsLoad';
import { useEffect, useMemo, useState } from 'react';
import { InputNumber, Form, Input, Select, message } from 'antd';
import { reasonRefusalList, rejectAndRefund, rejectUnpackException, rejectbuyerReturn, refusalOfReplacement } from '../../services';
import { find } from 'lodash';

const { TextArea } = Input;

//拒绝api映射
const refuseApi = {
	//拒绝仅退款
	'RefuseOnlyRefund': rejectAndRefund,

	//拒绝买家退货
	'RefuseBuyerReturn': rejectbuyerReturn,

	//拆包异常，拒绝退款
	'RefuseErrorRefund': rejectUnpackException,

	//拒绝补发/换货
	'RefuseExchange': refusalOfReplacement,
}

/** 拒绝用户的申请：退货&退款，补发，换货等 */
function RefuseBuyer(props) {
	const { item, selectKeys, tableList, handleOk, handleCancel } = props;
	const { refuseType, title } = item;
	const [isOk, setIsOk] = useState(false);
	const [loading, setLoading] = useState(false);
	const [form] = Form.useForm();
	const [open, setOpen] = useState(false);
	const [reasonList, setReasonList] = useState([]);

	//订单信息
	const afterSalesData = useMemo(() => {
		return find(tableList, ['id', selectKeys[0]]);
	}, [])

	//最大申请价格
	const goodsPrice = useMemo(() => {
		const arr = afterSalesData.goodsList;
		return arr.reduce((pre, next) => pre + next.ecGoodsPrice * next.goodsNum, 0);
	}, [afterSalesData])

	useEffect(() => {
		setOpen(true);
		const obj = find(tableList, ['id', selectKeys[0]]);
		if (obj.platRefundSn) {
			getRefuseReasonList();
		}
	}, [])

	//拒绝原因列表
	const getRefuseReasonList = async () => {
		setLoading(true);
		const { success, data } = await reasonRefusalList({
			id: afterSalesData.id,
			platRefundSn: afterSalesData.platRefundSn,
			ecStoreId: afterSalesData.ecStoreId,
			orderChannel: afterSalesData.orderChannel,
			afterType: afterSalesData.afterType
		})
		if (success) {
			const arr = [];
			data.map(v => {
				arr.push({
					value: v.reasonCode,
					label: v.reasonText,
				})
			})
			setReasonList(arr);
		}
		setLoading(false);
	}

	const onOk = () => {
		form.validateFields().then(async val => {
			console.log(val)
			handleReject(val);
		}).catch(err => console.log(err));
	}

	//拒绝操作
	const handleReject = async (val) => {
		const params = {
			ids: selectKeys,
			rejectType: afterSalesData.afterType,
			refundAmount: val.refundAmount,
			rejectRemarks: val.rejectRemarks,
			rejectImg: val.fileList ? val.fileList.map(v => v.response?.data?.fullPath).join() : undefined
		}
		if (afterSalesData.platRefundSn) {
			params.reasonCode = val.reasonCode;
			params.rejectReason = find(reasonList, ["value", val.reasonCode])?.label;
		} else {
			params.rejectReason = val.rejectReason;
		}
		setLoading(true);
		const { success } = await refuseApi[refuseType](params);
		setLoading(false);
		if (success) {
			message.success('操作成功');
			setIsOk(true);
			setOpen(false);
		}
	}

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		if (isOk) {
			handleOk()
		} else {
			handleCancel();
		}
	}

	const rules = [
		{ required: true, message: '请输入' }
	]

	const imgRules = [
		() => ({
			validator(rule, value) {
				if (!value || value.length == 0) {
					return Promise.reject(`请上传拒绝凭证`);
				}
				return Promise.resolve();
			},
		}),
	]

	const CommonImgsLoadProps = {
		upLoadText: "最多10张",
		maxCount: 10,
		handleOk(val) {
			form.setFieldsValue({
				fileList: val
			})
		}
	}

	const reasonCode = Form.useWatch('reasonCode', form);

	return (
		<CommonModal title={title} afterClose={afterClose} open={open} width="552px" onOk={onOk} onCancel={onCancel}>
			<Form
				name="refuse-buyer-modal-form"
				form={form}
				labelCol={{
					span: 4,
				}}
				wrapperCol={{
					span: 20,
				}}
				initialValues={{
					refundAmount: afterSalesData.refundAmount
				}}
				autoComplete="off"
			>
				{
					afterSalesData.platRefundSn ?
						<Form.Item
							label="拒绝原因"
							name="reasonCode"
							rules={[{ required: true, message: '请选择拒绝原因' }]}
						>
							<Select
								showSearch
								optionFilterProp="label"
								placeholder="请选择拒绝原因"
								options={reasonList}
							/>
						</Form.Item>
						:
						<Form.Item
							label="拒绝原因"
							name="rejectReason"
							rules={[{ required: true, message: '请输入拒绝原因' }]}
						>
							<Input placeholder='拒绝原因' maxLength={500} />
						</Form.Item>
				}
				{
					['21', '29'].includes(reasonCode) ?
						<Form.Item
							label="建议金额"
							name="refundAmount"
							rules={rules}
						>
							<InputNumber style={{ width: '100%' }} controls={false} addonAfter="元" precision={2} min={0} max={goodsPrice} />
						</Form.Item> : null
				}
				<Form.Item
					label="拒绝说明"
					name="rejectRemarks"
					rules={[{ required: true, message: '请输入拒绝说明' }]}
				>
					<TextArea rows={4} showCount placeholder="拒绝说明" maxLength={200} />
				</Form.Item>

				<Form.Item
					label="拒绝凭证"
					name="fileList"
					valuePropName="checked"
					rules={afterSalesData.orderChannel == 9 ? imgRules : []}
				>
					<CommonImgsLoad  {...CommonImgsLoadProps} />
				</Form.Item>
			</Form>
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default RefuseBuyer;